<template>
  <div class="maps">
    <div class="zhezhao"></div>
    <div id="container" class="mapsMain">
      <dv-loading style="position: absolute;z-index: 9999;color:white;" v-show="showLoading">Loading...</dv-loading>
      <picture-viewer ref="imageViewer2" style="z-index: 9999;"></picture-viewer>
    </div>

  </div>

</template>

<script>
  import PictureViewer from "@/components/picture-viewer/index-name";
  import AMap from 'AMap'
  import {getSlopeMapData} from '@/services/model/monitor-board'
  import constUrl from '@/services/env'
  import {

    PAGE_MONITORs,

  } from '@/utils/constant'
  import Vue from "vue";
  import {store} from "../../../monitor/work-point.store";

  // 地图渲染的图标
  const CURRENT_ICON_MAP = (item) => {
    switch (item.warningLevel) {

      case 1:
        return require('../imgs/icon1.png')
      case 2:
        return require('../imgs/icon2.png')
      case 3:
        return require('../imgs/icon3.png')
      case 4:
        return require('../imgs/icon4.png')
      case 5:
        return require('../imgs/icon5.png')
      default:
        return require('../imgs/icon1.png')

    }

  }
  // 渲染模板
  const HTML_CONT = (item) => {
    return `<div class="board_map-market" style="background: transparent ">
<!--      <p class="market_title" >${item.name}</p>-->
      <p class="market_info" style="color:white;font-size: 0.8vw;font-weight: 500">${item.warningLevelName}</p>
    </div>`
  }
  // 等级颜色
  const LEVEL_COLOR_MAP = {
    1: '#0DC26B',
    2: '#0073b7',
    3: '#f39c12',
    4: '#ff851b',
    5: '#e43321'
  }

  export default {
    components: {PictureViewer},
    data() {
      return {
        initData: '中国',
        showLoading: true,
        cluster: null, // 点聚合实例model
        constUrl,
        map: null,
        // 点标记集合
        markerList: [],
        projectMapDataList: [],
        damageMapDataList: [],
        // 是否展示弹窗
        isShowDialog: false,
        // 点聚合实例
        markerClusterer: null,
        colors: {}
      }
    },
    computed: {
      tabValue() {
        return this.$route.name
      },
      isControl() {
        if (this.$route.params.projectId) {
          return true
        }
        return false
      }
    },
    watch: {
      tabValue: 'getMarks'
    },
    methods: {

      init1(city) {//区域遮盖
        var that = this
        if (that.polygon) {
          that.map.remove(that.polygon)
        }
        AMap.plugin('AMap.DistrictSearch', function () {
          new AMap.DistrictSearch({
            extensions: 'all',
            subdistrict: 0
          }).search(city, function (status, result) {// 外多边形坐标数组和内多边形坐标数组
            var outer = [
              new AMap.LngLat(-560, 190, true),
              new AMap.LngLat(-160, -190, true),
              new AMap.LngLat(160, -190, true),
              new AMap.LngLat(560, 190, true)
            ]
            var holes = result.districtList[0].boundaries
            var pathArray = [outer]
            pathArray.push.apply(pathArray, holes)
            that.polygon = new AMap.Polygon({
              pathL: pathArray,
              strokeColor: '#5DFFF6',//城市边界颜色
              strokeWeight: 3,
              fillColor: '#191f36', // 遮罩背景色黑色
              fillOpacity: 0.8
            })
            that.polygon.setPath(pathArray)
            that.map.add(that.polygon)
          })
        })
        // that.map.setZoom(10) // 设置地图层级
      },
      refresh(projectId, typeCode, cityName) {
        if (cityName) {
          this.initData = cityName
        }
        if (!this.map) {

          this.initMap(this.$route.params.projectId)
          return
        }
        this.queryMapList(projectId, typeCode)
      },
      // 初始化地图
      initMap(projectId) {
        this.map = new AMap.Map('container', {
          resizeEnable: true,
          zoom: this.isControl ? 14 : 8,
          center: [107.21099490234, 26.72718055497],
          // mapStyle: 'amap://styles/dark'
          layers: [
            // 卫星
            new AMap.TileLayer.Satellite(),
            // 路网
            new AMap.TileLayer.RoadNet()
          ],
        })
        this.init1(this.initData)
        this.initPro(520000, 0)
        this.queryMapList(projectId)
        // this.initPro([520000, 330000, 610000], 0)
      },
      // 创建区域图层
      initPro(code, dep) {
        let that = this
        this.disProvince && disProvince.setMap(null)
        AMap.plugin(['AMap.DistrictLayer'], () => {
          this.disProvince = new AMap.DistrictLayer.Province({
            zIndex: 12,
            adcode: code,
            depth: dep,
            styles: {
              fill: function (properties) {
                // properties为可用于做样式映射的字段，包含
                // NAME_CHN:中文名称
                // adcode_pro
                // adcode_cit
                // adcode
                var adcode = properties.adcode
                return that.getColorByAdcode(adcode)
              },
              'province-stroke': 'cornflowerblue',
              'city-stroke': 'white', // 中国地级市边界
              'county-stroke': 'rgba(255,255,255,0.5)' // 中国区县边界
            }
          })
          this.disProvince.setMap(this.map)
        })

      },
      // 颜色辅助方法
      getColorByAdcode(adcode) {
        if (!this.colors[adcode]) {
          // var gb = Math.random() * 155
          this.colors[adcode] = 'rgba(' + 255 + ',' + 255 + ',255, 0.01)'
        }
        return this.colors[adcode]
      },
      // 查询地图数据
      async queryMapList(projectId, typeCode) {
        this.showLoading = true
        const res = await getSlopeMapData({projectId})
        this.projectMapDataList = res.data || []
        //项目控制台设置数据中第一个经纬度为中心点
        if (this.isControl && res.data[0] && res.data[0].longitude && res.data[0].latitude) {
          this.map.setCenter([res.data[0].longitude, res.data[0].latitude]);
        }
        this.mapDataList = this.projectMapDataList
        this.getMarks(typeCode)
      },
      // 查看大图
      previewImg(index, urls) {
        this.$refs.imageViewer.showViewer(urls.map(x => _this.constUrl + x.url), index)
      },
      // 查询地图数据
      getMarks(typeCode) {
        let mapDataList = this.mapDataList
        if (typeCode) {
          mapDataList = mapDataList.filter(x => x.warningLevel === typeCode)
        }
        // 信息窗口
        let _this = this
        this.markerClusterer?.removeMarkers(this.markerList)
        this.map.remove(this.markerList)
        this.showLoading = false
        let content =
          `<el-card class="box-card" style="z-index: 9999">
           <a @click="btnClose" class="btn-close amap-ui-infowindow-close amap-ui-smp-ifwn-def-tr-close">&#10006;</a>
           <div class="title ">{{windowInfoData.typeName}}详情<span style="float: right">{{windowInfoData.weather.weather}};{{windowInfoData.weather.temperature}}℃;{{windowInfoData.weather.humidity}}%</span></div>
                <ul>
                <li><span class="label_view" >项目名称：</span><span>{{windowInfoData.projectName}}</span></li>
                <li><span class="label_view" >工点名称：</span><span>{{windowInfoData.name}}</span></li>
                <li><span class="label_view" >预警等级：</span><span class="level_view" :style="gradeColor(windowInfoData.warningLevel)">{{windowInfoData.warningLevelName}}</span></li>
                </ul>
                <el-divider content-position="left"><span style="font-size: 12px;color: #ffffff">监测分项</span></el-divider>
          <div class="info-btn">
          <el-button type="success" class="btn-item" @click="toControl(item,windowInfoData.projectId)" v-for="item in windowInfoData.monitorPointList" size="mini">{{item.monitorTypeName}}</el-button>
          </div>
        <div class="demo-image__lazy" style="height:160px" v-if="windowInfoData.picList">
         <el-carousel trigger="click"  height="150px">
         <templ
          <el-carousel-item v-for="(item,index) in windowInfoData.picList" :key="index">
           <el-image style="height:150px;width:100%"  @click.stop="previewImg(index,windowInfoData.picList)" :src="constUrl+item.url" fit="cover"></el-image>
          </el-carousel-item>
        </el-carousel>
        </div>
        <picture-viewer ref="imageViewer"></picture-viewer>
        </div>
        </el-card>`
        let MyComponent = Vue.extend({
          template: content,
          components: {PictureViewer},
          data() {
            return {
              constUrl: '',
              msg: '边坡详情',

            }
          },
          props: {
            windowInfoData: {
              type: Object
            }
          },
          methods: {
            gradeColor(val) {
              switch (val) {
                case 1:
                  return 'background-color:#0DC26B;color:white'
                case 2:
                  return 'background-color:#0073b7;color:white'
                case 3:
                  return 'background-color:#f39c12;color:white'
                case 4:
                  return 'background-color:#ff851b;color:white'
                case 5:
                  return 'background-color:#e43321;color:white'
                default:
                  return 'background-color:#e43321;color:white'
              }
            },
            // 查看大图
            previewImg(index, urls) {

              const urlList = JSON.parse(JSON.stringify(urls));
              urlList.map((x) => {
                x.url = this.constUrl + x.url;
                return x;
              });
              // 显示照片查看器
              this.$refs.imageViewer.showViewer(urlList, index);
            },
            toControl(val, projectId) {
              _this.$router.push({
                path: `/project/${projectId}/work-point/${val.workPointId}/monitor/${val.monitorType}?activeId=${val.id}`
              })
            },
            btnClose() {
              _this.infoWindow.close(_this.map)
            },
          },
          created() {
            this.constUrl = _this.constUrl
          },
          mounted() {
            window.addEventListener("click", this.btnClose);
          }
        })
        this.markerList = mapDataList.filter(x => x.latitude && x.longitude)
          .map(x => {
            const {longitude, latitude} = x
            const marker = new AMap.Marker({
              position: [longitude, latitude],
              icon: CURRENT_ICON_MAP(x),
              offset: new AMap.Pixel(-18, -36),
              extData: x,
              iconLabel: 'test',
              // map:this.map  不用点聚合打开这里
            })
            marker.setLabel({
              offset: new AMap.Pixel(0, 30),  //设置文本标注偏移量
              content: HTML_CONT(x), //设置文本标注内容
              direction: 'top' //设置文本标注方位
            });
            // 监听单个点点击事件
            AMap.event.addListener(marker, 'click', e => {

              AMap.plugin('AMap.Weather', async function () {
              })
              //创建天气查询实例
              var weather = new AMap.Weather();
              //执行实时天气信息查询
              let extData = e.target.getExtData()
              let region = extData?.regionName?.split('-') || []
              region = region.length > 0 ? region : ['贵州']
              region = region[1] ? region[1] : region[0]
              weather.getLive(region, function (err, data) {
                extData.weather = data || {}
                extData.region = region
                // 窗体信息
                let component = new MyComponent({ // 传参
                  propsData: {
                    windowInfoData: extData
                  }
                }).$mount()
                _this.infoWindow = new AMap.InfoWindow({
                  content: component.$el, // 使用默认信息窗体框样式，显示信息内容
                  isCustom: true,
                  autoMove: true,
                  closeWhenClickMap: true,
                  retainWhenClose: true,
                  offset: new AMap.Pixel(0, -15),
                })
                _this.infoWindow.open(
                  _this.map,
                  marker.getPosition(e.lnt, e.lat)// 窗口信息的位置
                )
              })

            })
            // marker.on('mouseout', e => {
            //   const item = e.target.getExtData()
            // e.target.setContent(HTML_CONT[this.tabValue](item, CURRENT_ICON_MAP[this.tabValue]))
            // })
            return marker
          })
        if (typeCode) {
          this.map.setFitView(this.markerList)// 自适应显示点标记
          // this.map.setZoom(12) // 设置地图层级
        }
        this.map.add(this.markerList)
        //点聚合
        // this.addCluster()
      },
      // marks样式
      addCluster() {
        // 自定义图标
        var sts = [{
          url: '',
          size: new AMap.Size(32, 32),
          offset: new AMap.Pixel(-16, -16)
        }, {
          url: 'https://a.amap.com/jsapi_demos/static/images/green.png',
          size: new AMap.Size(32, 32),
          offset: new AMap.Pixel(-16, -16)
        }, {
          url: 'https://a.amap.com/jsapi_demos/static/images/orange.png',
          size: new AMap.Size(36, 36),
          offset: new AMap.Pixel(-18, -18)
        }, {
          url: 'https://a.amap.com/jsapi_demos/static/images/red.png',
          size: new AMap.Size(48, 48),
          offset: new AMap.Pixel(-24, -24)
        }, {
          url: 'https://a.amap.com/jsapi_demos/static/images/darkRed.png',
          size: new AMap.Size(48, 48),
          offset: new AMap.Pixel(-24, -24)
        }]

        AMap.plugin(['AMap.MarkerClusterer'], () => {
          this.markerClusterer = new AMap.MarkerClusterer(this.map, this.markerList, {
            styles: sts,
            gridSize: 200,
          })
        })
      }
      ,
    },
    mounted() {

    }
  }
</script>
<style lang="less" scoped>


  .map {
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    top: 0;
    background-color: #0e1014;
  }

  /deep/ .box-card {

    width: 400px;
    border-radius: 0.25rem;
    border: 1px solid #266BFF;
    z-index: 9999 !important;
    .el-divider__text {
      background-color: #1b1b1b !important;
      padding: 3px 10px;
      border-radius: 5px;
    }

    .btn-close {
      float: right;
      cursor: pointer;
    }

    .label_view {
      line-height: 30px;
      font-size: 13px;
      font-width: 600;
      margin-left: 10px;
      color: #1a253a;
    }

    .level_view {
      font-size: 12px;
      display: inline-block;
      padding: 0px 3px;
      border-radius: 3px;
    }

    .title {
      font-size: 20px;
      font-family: YouSheBiaoTiHei;
      white-space: nowrap;
      clear: both;
      background-color: #1a253a;
      margin-bottom: 15px;
      padding: 9px;
      color: white;
      border-radius: 5px;
    }

    .el-card__body {
      padding: 0 0.625rem;
      background: linear-gradient(to right, rgba(58, 80, 106, 0.5), #357c82);
      border-radius: 0.25rem 0.25rem 0 0;
      color: #ffffff;
      font-size: 20px;
      padding-bottom: 20px;
    }

    .el-button--success {
      color: #FFF;
      background-color: #1990FE;
      border-color: #1990FE;
    }

    .info-btn {
      margin-top: 5px;
      margin-bottom: 5px;

      .btn-item {
        margin-bottom: 7px;
        margin-right: 7px;
        background-color: #1990FE;
      }

      /deep/ .el-button + .el-button {
        margin-left: 0px;
      }
    }

    ul li {
      font-size: 13px;
      line-height: 20px;

      span:first-child {
        font-weight: bold;
      }
    }
  }
</style>
<style lang="less">
  .amap-marker-label {
    background: transparent !important;
    border-color: transparent;
  }

  .data-layer {
    position: absolute;
    bottom: -80px;
    left: 50%;
    transform: translateX(-50%);
    border-radius: 0.25rem;
    border: 1px solid #266BFF;
    margin-bottom: -1px;

    &::after {
      position: absolute;
      bottom: -10px;
      left: 50%;
      transform: translateX(-50%);
      content: '';
      display: block;
      border-top: 10px solid #266bff;
      width: 0;
      height: 0;
      border-left: 10px solid transparent;
      border-right: 10px solid transparent;
    }

    .data-layer-title {
      line-height: 2;
      padding: 0 0.625rem;
      background: linear-gradient(to right, rgba(25, 97, 241, 1), rgba(25, 97, 241, 0));
      border-radius: 0.25rem 0.25rem 0 0;
      color: #ffffff;
      font-size: 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .title {
        font-family: YouSheBiaoTiHei;
        white-space: nowrap;
        flex-shrink: 0;
      }

      .title_weather {
        margin-left: 8px;
        font-size: 14px !important;
        white-space: nowrap;
        flex-shrink: 0;
      }
    }
  }


  .data-layer .content {
    padding: 1.25rem 0.625rem;
    background: rgba(23, 36, 63, 0.8);
    border-radius: 0 0 0.25rem 0.25rem;
  }

  .data-layer .content p {
    color: #D5E3E8;
    font-size: 0.75rem;
    display: flex;
    align-items: flex-start;
    margin-bottom: 10px;
  }

  .layout-name {
    flex-shrink: 0;
    font-size: 20px;
    margin-right: 10px;
  }

  .layer-image {
    width: 80px;
    height: 80px;
    object-fit: 'fit'
  }

  .data-layer .content p .layer-num {
    white-space: nowrap;
    font-size: 1.25rem;
    color: #3BD5FD;
    font-weight: 600;
    padding-right: 1.25rem /* 20/16 */;
  }


</style>
<style lang="less">

  .zhezhao {
    position: absolute;
    width: 100%;
    height: 100%;
    background: url("../imgs/zhezhao.png") no-repeat;
    background-size: 100% 100%;
    z-index: 2;
    pointer-events: none;
    left: 0;
    top: 0;
  }

  .maps, .mapsMain {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
  }

  .custom-marker {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-wrap: nowrap;
    flex-direction: row;
    align-content: flex-start;

    .icon {
      width: 88px;
      height: 100px;
      background-size: 100% 100%;
      display: flex;
      justify-content: flex-start;
      align-items: flex-start;
      flex-wrap: nowrap;
      flex-direction: row;
      align-content: flex-start;
      position: relative;
      z-index: 10;

      .name {
        font-size: 24px;
        height: 38px;
        font-family: YouSheBiaoTiHei;
        font-weight: 400;
        color: #F0F0F0;
        width: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-wrap: nowrap;
        flex-direction: row;
        align-content: flex-start;
      }
    }
  }

</style>
